package com.design.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.design.config.CommonException;
import com.design.dao.entity.UserInfo;
import com.design.dao.mapper.UserInfoMapper;
import com.design.model.BaseResult;
import com.design.model.UserLogOnRequest;
import com.design.service.LoginService;
import com.design.utils.JwtOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Value("${manage.phone}")
    private String phone;


    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private JwtOperator jwtOperator;

    /**
     * 登录接口
     *
     * @param userLogOn 账号密码
     * @return token
     */
    public BaseResult<Map<String, String>> token(UserLogOnRequest userLogOn) {
        // 超级管理员
        Map<String, Object> claims = new HashMap<>();
        claims.put("phone", userLogOn.getPhone());
        claims.put("userType", userLogOn.getUserType());
        String token = jwtOperator.generateToken(claims);

        Map<String, String> result = new HashMap<>();
        result.put("token", token);

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        wrapper.eq("phone", userLogOn.getPhone());
        wrapper.eq("password", userLogOn.getPassword());
        List<UserInfo> userInfos = userInfoMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(userInfos)) {
            throw new CommonException("用户不存在或密码错误！");
        }
        for (UserInfo userInfo:userInfos
             ) {
            if (userLogOn.getUserType() == userInfo.getUserType()) {
                result.put("userId", String.valueOf(userInfo.getId()));
                return new BaseResult<>(result);
            }
        }
        throw new CommonException("用户类型错误！");
    }

    /**
     * 校验是否登录接口
     *
     * @return 是否登录
     */
    @Override
    public BaseResult<Boolean> tokenCheck(String token) {
        return new BaseResult<>(jwtOperator.validateToken(token));
    }
}
